import React, { useState, useEffect } from 'react';
import classnames from 'classnames';
import moment from 'moment';
import { connect } from 'dva';
import { Button, Form, Select, Table, Empty, Modal, Tag, message } from 'antd';
import TPage from '@/modules/TPage';
import GoodsModal from './modules/GoodsModal';
import Service from '@/public/http/services';
import { FictitiousGoodsType, GoodsType, GoodsClassify } from '@/public/constant/enums';
import style from './index.css';
const { Option } = Select;
const { Column } = Table;
const List: React.FC<any> = ({ total, list, dispatch }) => {
  const [curPage, setCurPage] = useState(1);
  const [curTitle, setCurTitle] = useState(null);
  const pageSize = 10;
  /**
   * 加载列表数据
   */
  function fetchList({ page, title }) {
    dispatch({
      type: 'homeManagement/fetchList',
      payload: {
        page,
        title,
        pageSize
      }
    })
  }

  /**
   * @desc 操作完更新列表
   */
  function reFetchList() {
    fetchList({
      page: curPage,
      title: curTitle
    })
  }


  useEffect(({ page = curPage, title = curTitle } = {}) => {
    fetchList({ page, title })
  }, [curPage, curTitle])
  // 渲染列表查询表单

  const handleQuery = (query) => {
    setCurPage(1);
    setCurTitle(query);
  }

  /**
   * @desc 设置首页商品
   * @param param0
   */
  const handleCancelSetHome = ({ id }) => {
    Modal.confirm({
      title: '确定要取消该首页商品？',
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        Service.setHomeGoods({
          id
        }).then(() => {
          message.info('取消成功');
          reFetchList();
        })
      }
    });
  }

  /**
 * @desc 设置banner
 * @param record
 */
  const handleSetBanner = ({ id }) => {

    Modal.confirm({
      title: '确定要将该商品设置为推荐商品？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        Service.setGoodsHot({
          id
        }).then(() => {
          message.info('设置成功');
          reFetchList();
        })
      }
    });
  }

  const handleCancelSetBanner = ({ id }) => {

    Modal.confirm({
      title: '确定确认取消该商品推荐位置？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        Service.cancelSetGoodsHot({
          id
        }).then(() => {
          message.info('取消设置成功');
          reFetchList();
        })
      }
    });
  }

  function renderTableForm() {
    const WrappedForm = Form.create<any>({ name: 'tableForm' })(function ({ form }) {
      const { getFieldDecorator } = form as any;
      return (
        <Form onSubmit={handleQuery.bind(null, form)} layout={'inline'}>

        </Form>
      );
    })
    return (
      <WrappedForm />
    );
  }

  // 根据渲染类型渲染列表
  const renderActions =
    (record: any) => {
      const { isHot } = record;
      return (
        <>
          {
            !isHot ? <Button className={style.mr8} type={'primary'} onClick={() => { handleSetBanner(record) }}>设置推荐</Button> :
              <Button className={style.mr8} onClick={() => { handleCancelSetBanner(record) }}>取消推荐</Button>
          }

          <Button className={style.mr8} type={'danger'} onClick={() => { handleCancelSetHome(record) }}>取消首页显示</Button>
        </>
      );
    }


  return (
    <TPage>
      <TPage.Title>首页商品管理列表</TPage.Title>
      <TPage.Table>
        <TPage.Layout className={style.action_block}>
          <TPage.Search
            placeholder={'请输入商品名称，可按回车键搜索'}
            onSearch={handleQuery}
          />
        </TPage.Layout>
        <TPage.Layout>
          {renderTableForm()}
        </TPage.Layout>
        <Table
          className={classnames(style.mt16, style.expert_list)}
          locale={{ emptyText: <Empty description={'无数据'} /> }}
          dataSource={list}
          pagination={{ total, current: curPage, pageSize, onChange: setCurPage }}
          rowKey={(record: any) => record.id}
        >
          <Column title={'编号ID'} width={64} dataIndex={'id'} key={'id'} />
          <Column title={'商品名称'} key={'username'}
            render={(value, record: any) => {
              return <span className={style.thumbnail}>
                < img src={record.imgs.split(',')[0]} />
                {record.title}
              </span>
            }}
          />
          <Column title={'所属分类'} dataIndex={'type'} key={'type'} render={(value) => <Tag color={value ? 'volcano' : 'cyan'}>{GoodsClassify[value]}</Tag>} />
          <Column title={'所属类目'} dataIndex={'cid'} key={'cid'} render={(value, record: any) => (record.type ? FictitiousGoodsType: GoodsType)[value]}/>
          <Column title={'价格(元)'} dataIndex={'price'} key={'price'} />
          <Column title={'商品状态'} dataIndex={'status'} key={'status'} render={value => <span className={value ? style.online : style.default}>{value ? '上架' : '下架'}</span>}/>
          <Column title={'更新时间'} dataIndex={'updateTime'} key={'updateTime'} render={(value) => value && moment(value).format('YYYY-MM-DD hh:mm:ss')} />
          <Column title={'创建时间'} dataIndex={'createTime'} key={'createTime'} render={(value) => value && moment(value).format('YYYY-MM-DD hh:mm:ss')} />
          <Column title={'操作'} key={'act'} render={renderActions} />
        </Table>
      </TPage.Table>
    </TPage>
  );
}
export default connect((state: any) => {
  return {
    list: state.homeManagement.list,
    total: state.homeManagement.total,
  };
})(List);
